package com.wangyadong.hobby.metric.report;

import com.codahale.metrics.*;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/12/1910:54
 * success rate
 * total business
 * total success
 * total failure
 * timer
 * volume bytes
 **/
public class JMXReportExample {
    private static final MetricRegistry metricRegistry = new MetricRegistry();
    private static final Counter totalBusiness = new Counter();
    private static final Counter successBusiness = new Counter();
    private static final Counter failrueBusiness = new Counter();

    private static final Timer timer = new Timer();
    //指数衰减
    private final static Histogram historm = new Histogram(new ExponentiallyDecayingReservoir());

    private static final RatioGauge ratioGauge = new RatioGauge() {
        @Override
        protected Ratio getRatio() {
            return Ratio.of(successBusiness.getCount(), totalBusiness.getCount());
        }
    };

    static {
        metricRegistry.register("cloud-disk-upload-total", totalBusiness);
        metricRegistry.register("cloud-disk-upload-success", successBusiness);
        metricRegistry.register("cloud-disk-upload-failrue", failrueBusiness);
        metricRegistry.register("cloud-disk-upload-frequency", timer);
        metricRegistry.register("cloud-disk-upload-volume", historm);
        metricRegistry.register("cloud-disk-upload-suc-ratio", ratioGauge);
    }

    private static final JmxReporter reporter = JmxReporter
            .forRegistry(metricRegistry)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS)
            .build();

    private static final ConsoleReporter consoleReporter = ConsoleReporter
            .forRegistry(metricRegistry)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS)
            .build();

    public static void main(String[] args) {
        consoleReporter.start(10, TimeUnit.SECONDS);
        reporter.start();
        while (true) {
            upload(new byte[ThreadLocalRandom.current().nextInt(10000)]);
        }

    }

    private static void upload(byte[] bytes) {
        Timer.Context context = timer.time();
        totalBusiness.inc();
        try {
            int x = 1 / ThreadLocalRandom.current().nextInt(100);
            TimeUnit.MILLISECONDS.sleep(200);
            historm.update(bytes.length);
            successBusiness.inc();
        } catch (Exception e) {
            System.out.println("==========处理失败====");
            failrueBusiness.inc();
        } finally {
            context.close();
        }
    }
}
